package me.zhengjie.app.action.interceptor;

import cn.hutool.core.util.IdUtil;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Objects;
import java.util.Properties;

/**
 * <p>
 * 自动字段操作拦截器
 * </p>
 *
 * @author zet
 * @date 2018/8/3 15:38
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class AuditFieldsOperationInterceptor implements Interceptor {

    private static final String CREATE_TIME = "createTime";

    private static final String UPDATE_TIME = "updateTime";

    private static final String ID = "id";


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        if (SqlCommandType.SELECT == sqlCommandType) {
            return invocation.proceed();
        }

        Object object = args[1];
        setAuditFields(object, sqlCommandType);
        return invocation.proceed();
    }

    /**
     * 设置审计字段
     * @param object 参数
     * @param type sql类型
     * @throws IllegalAccessException
     */
    private void setAuditFields(Object object, SqlCommandType type) throws IllegalAccessException {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields){
            field.setAccessible(true);
            if (Objects.isNull(field.get(object))){
                // 只有insert时，才根据是否传create_time等而设值
                if (SqlCommandType.INSERT == type){
                    if (Objects.equals(field.getName(), ID)){
                        field.set(object, IdUtil.fastSimpleUUID());
                    }
                    if (Objects.equals(field.getName(), CREATE_TIME)){
                        field.set(object, new Date());
                    }
                }

                // 公共操作，设置edit_time等
                if (Objects.equals(field.getName(), UPDATE_TIME)){
                    field.set(object, new Date());
                }
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
